from django.shortcuts import get_object_or_404, get_list_or_404
from django.contrib.auth.decorators import user_passes_test
from django.http import HttpResponse
from django.utils.translation import ugettext as _

from settings import ADMIN_BASE_URL

from common import djips_view
from common import get_related_objects
from models import Color, Folder, Image, Lang, ImageAttr

template_folder = 'djips/common/ajax/'

@djips_view('Admin')
def show_delete_color_message(request, color_id):
    """ Page rendering the overlay message used when deleting a color.
    """

    color = get_object_or_404(Color, pk = color_id)
    color_name = color.name
    color_related_objects = get_related_objects(color)

    form_action = '%s/djips_common/colors/delete/%s/' % (ADMIN_BASE_URL,
							 color_id)

    return 'delete_color_msg.html', {'confirm': True,
                                     'confirm_id': 'confirm_delete_image',
                                     'confirm_name': 'confirm',
                                     'confirm_value': _('Delete'),
                                     'cancel_value': _('Cancel'),
                                     'form_action': form_action,
                                     'form_method': 'POST',
                                     'color': color,
                                     'related_objects': color_related_objects}

@djips_view('Admin')
def delete_color(request, color_id):
    """ Deletes the asked color.
    """
    color = get_object_or_404(Color, pk = color_id)
    color_name = color.name

    # Yeah, there is absolutely no verification (except that the user
    # belongs to the staff. So calling this page directly deletes a
    # color image.
    # But you are not supposed to call this page direclty ;)
    color.delete()
    
    msg = _("Category '%(color_name)s' has been deleted." % 
	    {'color_name': color_name})
    return HttpResponse(msg)

@djips_view('Admin')
def images_ui(request):
    """ The Ajax powered UI to manage images.
    """
    try:
	root = Folder.objects.get(sup_folder=None)
    except Folder.DoesNotExist:
	# The user has never synchronized the system.
	root = None

    # We do not load any images at start, as there might be a lot
    # of them. Images will be loaded when the user selects a folder.
    filesystem_options = {'url': '%s'}
    return 'images_ui.html', {'root': root,
                              'filesystem_options': filesystem_options}

@djips_view('Admin')
def get_images(request, folder_id):
    """ View called to fill the content of the previous view
    center field.
    """

    folder = get_object_or_404(Folder, pk = folder_id)
    return 'images_ui_main.html', {'images': folder.all_images(),
                                   'wrapper': True}

@djips_view('Admin')
def get_full_image_url(request, image_id):
    """ Returns the image's picture URL.
    """
    image = get_object_or_404(Image, pk = image_id)
    return HttpResponse(image.file.url)

@djips_view('Admin')
def make_image_dia(request, image_id, wrapper=True):
    image = get_object_or_404(Image, pk = image_id)
    return 'single_image.html', {'image': image,
                                 'wrapper': wrapper}

@djips_view('Admin')
def get_image_properties_form(request, image_id):
    image = get_object_or_404(Image, pk = image_id)
    langs = Lang.objects.filter(activated=True)
    colors = Color.objects.all()

    titles = {}
    descriptions = {}
    for lang in langs:
	try:
	    attr = image.attributes.get(lang = lang)
	    titles[lang.id] = attr.title
	    descriptions[lang.id] = attr.description
	except:
	    pass

    return 'image_property_form.html', {'image': image,
                                        'langs': langs,
                                        'colors': colors,
                                        'titles': titles,
                                        'descriptions': descriptions}
    
@djips_view('Admin')
def save_image_properties(request, image_id):
    image = get_object_or_404(Image, pk = image_id)    
    langs = Lang.objects.filter(activated=True)

    if request.method == 'GET':
	return HttpResponse('')

    form = request.POST
    if 'cancel' in form:
	return HttpResponse('')

    if 'mark' in form:
	image.mark = form['mark']

    if 'color' in form:
	try:
	    color = Color.objects.get(id = form['color'])
	    image.color_flag = color
	except:
	    # No color selected
	    image.color_flag = None

    image.update_tags(form['tags'])

    for lang in langs:
	title_field = 'title_' + lang.id
	desc_field = 'desc_' + lang.id
	if not title_field in form and \
	    not desc_field in form:
	    # This shall not happen.
	    continue

	if not form[title_field] and not form[desc_field]:
	    # Not data for this language.
	    continue

	try:
	    attr = ImageAttr.objects.get(image = image,
					 lang = lang)
	except ImageAttr.DoesNotExist:
	    attr = ImageAttr(image = image, lang = lang)

	if title_field in form:
	    attr.title = form[title_field]
	if desc_field in form:
	    attr.description = form[desc_field]

	attr.save()
    image.save()
    
    # We render the dia of the image which will be replaced in the interface.
    return make_image_dia(request, image.id)


@djips_view('Admin')
def spray(request, image_id):
    image = get_object_or_404(Image, pk = image_id);
    modes = ['mark', 'color', 'tag']

    if not 'mode' in request.GET:
	return
    mode = request.GET['mode']
    if not mode in modes:
	return

    if not 'value' in request.GET:
	return
    value = request.GET['value']


    if mode == 'mark':
	try:
	    value = int(value)
	except ValueError:
	    return

	if value < 0 or value > 5:
	    value = 0

	image.mark = value

    elif mode == 'color':
	try:
	    color = Color.objects.get(id = value)
	except Color.DoesNotExist:
	    color = None

	image.color_flag = color

    image.save()
    return make_image_dia(request, image.id, wrapper = False)
    
